package cn.com.fssg.platform.base.handler.impl.gsl.zw;

import cn.com.fssg.platform.base.handler.InterfaceHandler;
import cn.com.fssg.platform.biz.BizUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * @Description: 工商联履职考核列表接口
 */
@Component
public class GslZwSelectListCtl implements InterfaceHandler {

    private NamedParameterJdbcTemplate jdbcTemplate = BizUtil.cur().tenantMainJdbcTemplate();

//    @Autowired
//    private NamedParameterJdbcTemplate jdbcTemplate;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Object run(HttpServletRequest request, JSONObject jsonObject) throws Exception {
        JSONObject pagination = jsonObject.getJSONObject("pagination");
        JSONArray searchList = jsonObject.getJSONArray("searchList");
        String userNameQuery = "";
        //拼接查询条件
        List <String> queryParamList = new ArrayList<>();
        if(!searchList.isEmpty()) {
            for (Object search : searchList) {
                Map<String, Object> param = (Map<String, Object>) search;
                String key = param.get("fieldName").toString();
                //获取查询条件是否为姓名，如果是，则先加密
                if ("username".equalsIgnoreCase(key)) {
                    String fieldValue = param.get("fieldValue").toString();
                    userNameQuery = fieldValue;
                } else {
                    queryParamList.add(key + " = '" + param.get("fieldValue") + "'");
                }
            }
        }
        String queryParam = " and 1 = 1 ";
        if (!queryParamList.isEmpty()) {
            queryParam = StringUtils.join(queryParamList, " and ");
        }
        //select * from gsl_jc_zw_user where gsl_session = '{QueryString('jcId')}'
        String querySql = "select * from gsl_jc_zw_user where gsl_session = :jcId %s order by create_date desc ";

        String paginationSql = String.format(querySql, queryParam);
        Map<String, Object> param = new HashMap<>();
        param.put("jcId", jsonObject.getString("jcId"));
        List<Map<String, Object>> list = jdbcTemplate.queryForList(paginationSql, param);
        List<Map<String, Object>> dataList = new ArrayList<>();
        if (!list.isEmpty()) {
            for (Map<String, Object> map : list) {
                String name = (String) map.get("username");
                String userName = decrypt(name, "usertokon");
                if(userNameQuery.isEmpty()) {
                    dataList.add(map);
                } else {
                    if (userName.contains(userNameQuery)) {
                        dataList.add(map);
                    }
                }

            }
        }
        //封装返回方法
        Map<String, Object> result = new HashMap<>();
        if(!list.isEmpty()) {
            result.put("count", dataList.size());
            result.put("dataList", dataList);
        }
        return result;
    }

    public static final String ALGORITHM = "AES";

    // 密钥补全
    public static byte[] padKey(byte[] key, int length) {
        return Arrays.copyOf(key, length);
    }

    /**
     * HEX 字符串转字节数组
     */
    public static byte[] hexToBytes(String hex) {
        byte[] bytes = new byte[hex.length() / 2];
        for (int i = 0; i < bytes.length; i++) {
            bytes[i] = (byte) Integer.parseInt(hex.substring(i * 2, i * 2 + 2), 16);
        }
        return bytes;
    }

    /** 解密 */
    public static String decrypt(String input, String keys) throws Exception {
        // 1. HEX 字符串 → 字节数组
        byte[] cipherBytes = hexToBytes(input);
        byte[] keyBytes = padKey(keys.getBytes(StandardCharsets.UTF_8), 16);
        SecretKeySpec key = new SecretKeySpec(keyBytes, ALGORITHM);
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte[] decrypted = cipher.doFinal(cipherBytes);
        return new String(decrypted, StandardCharsets.UTF_8);
    }
}
